<?php

namespace common\modules\pms\models;

use common\behaviors\TimestampBehavior;
use common\components\ActiveRecord;
use Yii;
use yii\db\Expression;

/**
 * This is the model class for table "{{%pms_project}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $alias
 * @property string $description
 * @property integer $start_time
 * @property integer $end_time
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $created_by
 * @property integer $updated_by
 * @property Task[] $tasks
 */
class Project extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%pms_project}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['description'], 'string'],
            [['alias', 'start_time', 'end_time'], 'safe'],
            [['name'], 'string', 'max' => 65]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app/pms', 'ID'),
            'name' => Yii::t('app/pms', 'Name'),
            'alias' => Yii::t('app/pms', 'Alias'),
            'description' => Yii::t('app/pms', 'Description'),
            'start_time' => Yii::t('app/pms', 'Start Time'),
            'end_time' => Yii::t('app/pms', 'End Time'),
            'created_at' => Yii::t('app/pms', 'Created At'),
            'updated_at' => Yii::t('app/pms', 'Updated At'),
            'created_by' => Yii::t('app/pms', 'Created By'),
            'updated_by' => Yii::t('app/pms', 'Updated By'),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors[] = [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'created_at',
            'updatedAtAttribute' => 'updated_at',
            'value' => new Expression('NOW()'),
        ];
        
        return $behaviors;
    }

    /**
     * {@inheritdoc}
     */
    public function beforeSave($insert)
    {
        if ( ! is_numeric($this->start_time))
        {
            $this->start_time = strtotime($this->start_time);
        }
        if ( ! is_numeric($this->end_time))
        {
            $this->end_time = strtotime($this->end_time);
        }
        return parent::beforeSave($insert);
    }

    /**
     * @return Task[]
     */
    public function getTasks()
    {
        return $this->hasMany(Task::className(), [
            'project_id' => 'id',
        ]);
    }
}
